<template>
  <div>
    <el-input v-model="search" placeholder="请输入用户名搜索"></el-input>
    <el-button class="search" @click="getUserList()" type="primary" size="small"
      >搜索</el-button
    >
    <el-button @click="resetSearch()" type="warning" size="small"
      >重置</el-button
    >
    <el-button @click="handleClickAdd()" type="primary" size="small"
      >新增用户</el-button
    >

    <el-table :data="tableData" style="width: 100%">
      <el-table-column width="100px" label="序号" type="index">
        <!--序号连续-->
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="150">
      </el-table-column>
      <el-table-column prop="nickname" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="photo" label="头像" width="200">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.photo"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="isPresident" label="是否为会长" width="120">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200">
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="200">
      </el-table-column>
      <el-table-column prop="resetPassword" label="重置密码" width="100">
        <template slot-scope="scope">
          <el-button
            @click="resetPassword(scope.$index, scope.row)"
            type="text"
            size="small"
            >重置</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            @click="handleClickDelete(scope.$index, scope.row)"
            type="text"
            size="small"
            >删除</el-button
          >
          <el-button
            @click="handleClick(scope.$index, scope.row)"
            type="text"
            size="small"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 	修改 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" style="width: 210px"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="nickname">
          <el-input v-model="ruleForm.nickname" style="width: 210px"></el-input>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload
            action=""
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :http-request="myUpload"
            :file-list="fileList"
            :auto-upload="false"
            ref="upload"
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible2">
            <img :src="dialogImageUrl" alt="" />
          </el-dialog>
          <el-button
            type="primary"
            @click="submitUpload(1)"
            style="margin-left: 10px"
            >上传</el-button
          >
        </el-form-item>

        <el-form-item label="是否为会长" prop="isPresident">
          <el-radio-group v-model="ruleForm.isPresident">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上次更新时间" prop="updateTime">
          <el-input
            v-model="ruleForm.updateTime"
            style="width: 210px"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>

    <!--新增用户-->
    <el-dialog
      title="新增用户"
      :visible.sync="dialogVisible3"
      :close-on-click-modal="false"
      width="30%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" style="width: 210px"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="ruleForm.defaultPassword"
            style="width: 210px"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="nickname">
          <el-input v-model="ruleForm.nickname" style="width: 210px"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            action=""
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :http-request="myUpload"
            :auto-upload="false"
            ref="upload"
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible2">
            <img :src="dialogImageUrl" alt="" />
          </el-dialog>
          <el-button
            type="primary"
            @click="submitUpload(1)"
            style="margin-left: 10px"
            >上传</el-button
          >
        </el-form-item>
        <el-form-item label="是否为会长" prop="isPresident">
          <el-radio-group v-model="ruleForm.isPresident">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="addSubmitForm()">确 定</el-button>
      </span>
    </el-dialog>
    <!--分页-->
    <div class="block" align="right">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 4, 5, 6]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import request from '@/api/request'
import index from '@/views/Index.vue'

export default {
  name: 'UserManage',
  computed: {
    index() {
      return index
    },
  },
  data() {
    return {
      // 分页展示的数据
      tableData: [],
      pageSize: 6,
      currentPage: 1,
      totalCount: 0,
      // 搜索框
      search: '',
      fileList: [],
      /*选项卡*/
      inputVisible: true,
      disable: false,
      /* 修改对话框 */
      dialogVisible: false,

      /*上传图片*/
      dialogImageUrl: '',
      dialogVisible2: false,
      //新增对话框
      dialogVisible3: false,

      ruleForm: {
        id: '',
        username: '',
        password: '',
        password2: '',
        defaultPassword: '123456',
        nickname: '',
        photo: '',
        isPresident: '',
        createTime: '',
        updateTime: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '长度在 6 到 18 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    getUserList() {
      if (this.search) {
        this.currentPage = 1
      }
      request
        .get('/admin/studentlist', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            username: this.search,
          },
        })
        .then((res) => {
          console.log(res)
          this.tableData = res.data.items
          this.totalCount = res.data.total
        })
    },

    handleSizeChange: function (size) {
      //size是该函数自带的参数，代表变化后的每页显示的条数
      this.pageSize = size
      this.getUserList()
    },

    handleCurrentChange: function (currentPage) {
      //currentPage是该函数自带的参数，代表变化后的页码
      this.currentPage = currentPage
      this.getUserList()
    },

    //重置搜索框
    resetSearch() {
      this.search = ''
      this.getUserList()
    },

    //重置密码
    resetPassword(index, row) {
      request
        .patch('/admin/resetPwd', {
          username: row.username,
        })
        .then((res) => {
          console.log(res)
          if (res.code === 200) {
            this.$message.success('重置成功')
          } else {
            this.$message.error('重置失败')
          }
        })
    },

    //删除用户
    handleClickDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          request
            .delete('/admin/deleteuser', {
              params: {
                id: row.id,
              },
            })
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(res.message)
                setTimeout(() => {
                  this.getUserList()
                })
              } else {
                this.$message.error(res.message)
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },

    //弹出新增对话框
    handleClickAdd() {
      this.dialogVisible3 = true
    },

    //新增用户表单提交
    addSubmitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          request
            .post('/admin/insertuser', {
              username: this.ruleForm.username,
              password: this.ruleForm.password,
              nickname: this.ruleForm.nickname,
              photo: this.dialogImageUrl,
              isPresident: this.ruleForm.isPresident,
            })
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(res.message)
                setTimeout(() => {
                  this.dialogVisible3 = false
                  this.getUserList()
                })
              } else {
                this.$message.error(res.message)
              }
            })
        }
      })
    },

    //弹出修改对话框
    handleClick(index, row) {
      this.fileList = []
      this.dialogVisible = true
      this.ruleForm = row
      this.fileList.push({ name: '123.jpg', url: this.ruleForm.photo })
    },

    //提交修改
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          request
            .patch('/admin/updateuser', {
              id: this.ruleForm.id,
              username: this.ruleForm.username,
              password: this.ruleForm.password,
              nickname: this.ruleForm.nickname,
              photo: this.dialogImageUrl,
              isPresident: this.ruleForm.isPresident,
            })
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(res.message)
                setTimeout(() => {
                  this.dialogVisible = false
                  this.getUserList()
                })
              } else {
                this.$message.error(res.message)
              }
            })
        }
      })
    },

    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible2 = true
    },

    submitUpload(value) {
      if ((value = 1)) {
        //上传图片
        //找到ref为upload的上传组件，调用该组件的submit方法,会自动调用:http-request指定的方法
        this.$refs['upload'].submit()
      }
    },

    //上次文件到服务器
    myUpload(content) {
      //content.file就是要上传的文件
      //FormData可以用于处理文件对象
      var param = new FormData()
      param.append('file', content.file)
      request({
        url: '/upload',
        method: 'post',
        data: param,
      }).then((res) => {
        if (res.code === 200) {
          this.dialogImageUrl = res.data
          this.$message.success(res.message)
        }
      })
    },

    //限制文件选择数量
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
      )
    },
  },
  mounted() {
    this.getUserList()
  },
}
</script>

<style scoped>
.el-input {
  width: 300px;
  padding-left: 50px;
}
.search {
  margin-left: 20px;
}
</style>
